package com.example.demo.controller;

import com.example.demo.entity.Store;
import com.example.demo.entity.User;
import com.example.demo.pojo.BSResult;
import com.example.demo.service.StoreService;
import com.example.demo.service.UserService;
import com.example.demo.utils.BSResultUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;

@Controller
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;


    @Autowired
    private StoreService storeService;

    @RequestMapping("/register")
    public String register(User user, Model model){

        BSResult check=this.checkUserExist(user.getUsername());
        if((Boolean)check.getData()){

            try{
                BSResult save= userService.save(user);
                model.addAttribute("username", user.getUsername());
                return "register_success";

            }catch(Exception e){
                e.printStackTrace();
                model.addAttribute("registerError", check.getMessage());
                return "fail";
            }
        }
        else {

            model.addAttribute("registerError","您已经登录网站了");
            return "register";
        }

    }

    @RequestMapping("/checkUserExist")
    @ResponseBody
    public BSResult checkUserExist(String username){


        if(username==null){
            return BSResultUtils.build(200,"用户名不能为空",false);
        }
        else
        return userService.checkUserByUsername(username);

    }


    @RequestMapping("/login")
    public String userLogin(User user,String rememberMe,Model model,HttpServletRequest request){

        Subject subject= SecurityUtils.getSubject();


        if(!subject.isAuthenticated()){
            String password= DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(password);
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),password);
            token.setRememberMe(false);//禁止记住我功能
            if("rememberMe".equals(rememberMe))
                token.setRememberMe(true);
            else
                token.setRememberMe(false);

            try{
                subject.login(token);
                System.out.println("Login is successful!");
                User loginUser=(User)subject.getPrincipal();
                HttpSession session=request.getSession();
                session.setAttribute("loginUser",loginUser);

                Store store=storeService.findStoreByUserId(loginUser.getUserId());
                session.setAttribute("loginStore",store);




                SavedRequest savedRequest = WebUtils.getSavedRequest(request);
                String url = "/";
                if (savedRequest != null) {
                    url = savedRequest.getRequestUrl();
                    String s=request.getContextPath();
                    System.out.println(s);

                    if(url.contains(request.getContextPath())){
                        url = url.replace(request.getContextPath(),"");
                    }
                }
                if(StringUtils.isEmpty(url) || url.equals("/favicon.ico")){
                    url = "/";
                }

                return "redirect:" + url;
            }catch(UnknownAccountException | IncorrectCredentialsException uae){
                        uae.printStackTrace();
                         model.addAttribute("loginMsg","用户名或密码错误");
                         return "login";
            }catch (AuthenticationException ae) {
                model.addAttribute("loginMsg", "登录失败！");
                return "login";
            }
        }
        else{
            return "redirect:/index";
        }
    }


    @RequestMapping("/info")
    public String userInfo(){
        return "user_info";
    }

    @ResponseBody
    @RequestMapping("/update")
    public BSResult update(HttpSession session,User user,MultipartFile pictureFile,HttpServletRequest request) throws IOException {

        User loginUser = (User) session.getAttribute("loginUser");

        if(!loginUser.getImageUrl().contains("original.jpg")){
            String firstPath=request.getServletContext().getRealPath("/"
                    +loginUser.getImageUrl().substring(loginUser.getImageUrl().lastIndexOf(File.separator)+1));
            File originalFile=new File(firstPath);
            originalFile.delete();
        }
        loginUser.setNickname(user.getNickname());
        loginUser.setPhone(user.getPhone());
        loginUser.setGender(user.getGender());
        loginUser.setIdentity(user.getIdentity());
        loginUser.setLocation(user.getLocation());
        loginUser.setDetailAddress(user.getDetailAddress());





        if(pictureFile!=null){
                if(pictureFile.getOriginalFilename()!=null ){
                    String webPath=request.getServletContext().getRealPath("/"+"upload/usericon");
                    String oldFileName=pictureFile.getOriginalFilename();
                    String newFileName= RandomStringUtils.randomAlphanumeric(8)+oldFileName.substring(oldFileName.lastIndexOf("."));
                    File file=new File(webPath+File.separator+newFileName);
                    pictureFile.transferTo(file);
                    loginUser.setImageUrl("upload/usericon"+File.separator+newFileName);
                }
        }

        loginUser.setUpdated(new Date());
        session.setAttribute("loginUser", loginUser);
        BSResult result = userService.updateUser(loginUser);

        return result;
    }


    @ResponseBody
    @RequestMapping("/password/{userId}")
    public BSResult updatePassword(String oldPassword, String newPassword, @PathVariable Integer userId){

        if(oldPassword==null || newPassword==null)
            return BSResultUtils.build(400,"密码不可以为空");

        return userService.compareAndChangePwd(userId,oldPassword,newPassword);

    }









    @RequestMapping("/logout")
    public String logout(){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/index";
    }




}
